{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Using Financial Data Example #1: Calculating Altman Z\" Score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Professor Altman first formulated his infamous \"Z Score\" in [1968](http://www.defaultrisk.com/_pdf6j4/Financial_Ratios_Discriminant_Anlss_n_Prdctn_o_Crprt_Bnkrptc.pdf) while at NYU. The \"Z Score\" attempts to quantify the likelihood that a company defaults. After several iterations, the Altman Z\" (Double Prime) Score was developed to better quantify a company's credit risk. Professor Altman's presentation [here](http://pages.stern.nyu.edu/~ealtman/3-%20CopCrScoringModels.pdf) walks through several models including this one. When it was initially developed there were some crude cutoffs for the scores - above 2.6 and the firm was \"healthy\", between 1.1-2.6 was the \"grey area\", and below 1.1 and the firm as at risk of bankruptcy. However, over time that crude scale was refined. One of the unique things about the Altman Z\" Score today is that we have a mapping to conventional credit ratings. Below we walk through the example of calculating the score from scratch using [IEX data](https://iextrading.com/developer/docs/)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$$ Z” = 6.56x_1 +3.26x_2 + 6.72x_3 + 1.05x_4 $$\n",
    "$$ \\textrm{Where:} $$\n",
    "$$ x_1 = \\textrm{Working Capital / Total Assets} $$\n",
    "$$ x_2 = \\textrm{Retained Earnings / Total Assets} $$\n",
    "$$ x_3 = \\textrm{EBIT / Total Assets} $$\n",
    "$$ x_4 = \\textrm{Market Value of Equity / Total Liabilities} $$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pyEX as p\n",
    "c = p.Client(api_token=\"pk_353fe2ce67cd4c16b30a748ff783c865\", version=\"v1\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ticker = \"aapl\"\n",
    "incomeStatement = c.incomeStatementDF(ticker)\n",
    "balanceSheet = c.balanceSheetDF(ticker)\n",
    "cfStatement = c.cashFlowDF(ticker)\n",
    "stats = c.keyStats(ticker)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x1 = ( balanceSheet[\"currentAssets\"][0] - balanceSheet[\"totalCurrentLiabilities\"][0] ) / balanceSheet[\"totalAssets\"][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x2 = balanceSheet[\"retainedEarnings\"][0] / balanceSheet[\"totalAssets\"][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x3 = incomeStatement[\"ebit\"][0] / balanceSheet[\"totalAssets\"][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x4 = stats[\"marketcap\"] / balanceSheet[\"totalLiabilities\"][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "6.56 * x1 + 3.26 * x2 + 6.72 * x3 + 1.05 * x4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def altmanZDoublePrime( ticker ):\n",
    "    '''\n",
    "    Calculate the Altman Z\" Score for a given ticker\n",
    "    \n",
    "    ticker = string, user input for which to calculate the Z-score. Not case sensitive.\n",
    "    '''\n",
    "    incomeStatement = c.incomeStatementDF(ticker)\n",
    "    balanceSheet = c.balanceSheetDF(ticker)\n",
    "    cfStatement = c.cashFlowDF(ticker)\n",
    "    stats = c.keyStats(ticker)\n",
    "    x1 = ( balanceSheet[\"currentAssets\"][0] - balanceSheet[\"totalCurrentLiabilities\"][0] ) / balanceSheet[\"totalAssets\"][0]\n",
    "    x2 = balanceSheet[\"retainedEarnings\"][0] / balanceSheet[\"totalAssets\"][0]\n",
    "    x3 = incomeStatement[\"ebit\"][0] / balanceSheet[\"totalAssets\"][0]\n",
    "    x4 = stats[\"marketcap\"] / balanceSheet[\"totalLiabilities\"][0]\n",
    "    return 6.56 * x1 + 3.26 * x2 + 6.72 * x3 + 1.05 * x4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "altmanZDoublePrime(\"aapl\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "def altmanZDPImpliedRating( ticker ):\n",
    "    '''\n",
    "    Calculate the implied credit rating from a company's Altman Z\" Score \n",
    "    \n",
    "    ticker = string, user input for which to calculate the Z-score. Not case sensitive.\n",
    "    '''\n",
    "    adjZScore = 3.25 + altmanZDoublePrime( ticker )\n",
    "    zMap = [ 8.15, 7.6, 7.3, 7., 6.85, 6.65, 6.4, 6.25, 5.85, 5.65, 5.25, 4.95, 4.75, 4.5, 4.15, 3.75, 3.2, 2.5, 1.75 ]\n",
    "    scores = [ \"AAA\", \"AA+\", \"AA\", \"AA-\", \"A+\", \"A\", \"A-\", \"BBB+\", \"BBB\", \"BBB-\", \"BB+\", \"BB\", \"BB-\", \"B+\", \"B\", \"B-\", \"CCC+\", \"CCC\", \"CCC-\", \"D\" ] \n",
    "    return scores[ zMap.index( np.array( zMap )[ np.array( zMap ) < adjZScore ].max() ) ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "altmanZDPImpliedRating(\"aapl\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
